<template>
  <div id="register-details">
    <el-drawer append-to-body v-model="drawer" :title="`明细ID【${registerInfo.ibDetailId}】-收货登记`" direction="rtl"
      size="50%">
      <el-card class="detail-card" shadow="hover">
        <el-form ref="register" :model="registerData" :rules="registerRules" class="detail-form" label-position="right"
          label-width="100px">
          <el-form-item label="明细ID" prop="ibDetailId">
            <el-input v-model="registerData.ibDetailId" disabled />
          </el-form-item>
          <el-form-item label="订单号" prop="ebeln" v-show="registerData.ibMasterType == 'PO_IN_WIP'">
            <el-input v-model="registerData.ebeln" disabled />
          </el-form-item>
          <el-form-item label="订单行号" prop="ebelp" v-show="registerData.ibMasterType == 'PO_IN_WIP'">
            <el-input v-model="registerData.ebelp" disabled />
          </el-form-item>
          <el-form-item label="标签号" prop="labelNo" v-show="registerData.ibMasterType == 'WO_IN_FG'">
            <el-input v-model="registerData.labelNo" disabled />
          </el-form-item>
          <el-form-item label="箱号" prop="barcode" v-show="registerData.ibMasterType == 'WO_IN_FG'">
            <el-input v-model="registerData.barcode" disabled />
          </el-form-item>
          <el-form-item label="物料编号" prop="spuNo">
            <el-input v-model="registerData.spuNo" disabled />
          </el-form-item>
          <el-form-item label="物料名称" prop="spuName">
            <el-input v-model="registerData.spuName" disabled />
          </el-form-item>
          <el-form-item label="容器编号" prop="contNo">
            <el-input v-model="registerData.contNo" @input="handleQRCodeInput" placeholder="请输入或扫描条码" autofocus />
          </el-form-item>
          <el-form-item label="收货站台" prop="stationNo">
            <el-select v-model="registerData.stationNo" placeholder="请选择站台编号" clearable>
              <el-option v-for="item in stationOptions" :key="item.stationNo" :label="item.stationName"
                :value="item.stationNo" />
            </el-select>
          </el-form-item>
          <el-form-item label="RELID" prop="reelId" v-show="registerData.ibMasterType == 'PO_IN_WIP'">
            <el-input v-model="registerData.reelId" />
          </el-form-item>
          <el-form-item label="收货数量" prop="inQty">
            <el-input-number v-model="registerData.inQty" :step="1" :min=0 :max=999999 />
          </el-form-item>
          <el-form-item label="批次号" prop="lotNo" v-show="registerData.ibMasterType == 'PO_IN_WIP'">
            <el-input v-model="registerData.lotNo" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="goRegister">收货登记</el-button>
            <el-button type="success" @click="goRelase">入库放行</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-drawer>
  </div>
</template>

<script setup name="register-details">
import { ElMessage } from 'element-plus'
import WmsTable from '@/components/WmsTable/index.vue'
import WmsForm from '@/components/WmsForm/index.vue'
import { ibFgRegister, ibWipRegister, ibReturnRegister, ibRelease } from "@/api/wms/ibRegister.js";
import { listIbDetails, getIbDetails, delIbDetails, addIbDetails, updateIbDetails } from "@/api/wms/ibDetails";
import { data } from './index.js'
import { listStation } from "@/api/wms/station";
import { reactive, ref, onMounted } from 'vue';
import { parseQRCodeCombined } from '@/utils/qrCodeParser';

const emit = defineEmits(['refresh'])
let drawer = defineModel()

let register = ref()
const props = defineProps({
  registerInfo: {
    type: Object,
    default: () => { }
  }
})

const dataReactive = reactive(data);
const { queryParams, stationParams, form, rules } = toRefs(dataReactive);

const { proxy } = getCurrentInstance();

const registerData = ref({
  ibDetailId: null,
  ibMasterType: null,
  ebeln: null,
  ebelp: null,
  labelNo: null,
  barcode: null,
  spuNo: null,
  spuName: null,
  stationNo: null,
  contNo: null,
  reelId: null,
  inQty: 0,
  lotNo: null
});

// 站台选项数组
const stationOptions = ref([]);

const registerRules = {
  contNo: [
    { required: true, message: "容器编号不能为空", trigger: "blur" }
  ],
  stationNo: [
    { required: true, message: "登记站台不能为空", trigger: "blur" }
  ],
  inQty: [
    { required: true, message: "收货数量不能为空", trigger: "blur" }
  ]
}

// 处理二维码输入
function handleQRCodeInput(value) {
  if (!value) return;

  // 检查输入值是否可能是二维码（包含花括号）
  if (value.includes('{')) {
    // 解析二维码信息
    const result = parseQRCodeCombined(value);

    if (result.success) {
      const { barcode, lotNo } = result.data;

      // 自动填充表单
      if (barcode) {
        registerData.value.contNo = barcode;
        registerData.value.reelId = barcode;
      }

      if (lotNo) {
        registerData.value.lotNo = lotNo;
      }

      // 提示成功
      ElMessage.success('扫码二维码解析成功');
    } else {
      // 解析失败时提示
      registerData.value.contNo = "";
      registerData.value.reelId = "";
      ElMessage.warning('二维码解析失败: ' + result.message);
    }
  }
  // 如果不是二维码格式，则保持原样（普通的容器编号输入）
}

// 根据detailId获取数据
function getDetailInfo() {
  getIbDetails(props.registerInfo.ibDetailId).then((response) => {
    registerData.value = response.data;
    // 计算单据可收数量
    console.log("计划数量：", response.data.ibPlanQty, "已收数量：", response.data.ibActualQty, "可收数量：", response.data.ibPlanQty - response.data.ibActualQty);
    registerData.value.inQty = response.data.ibPlanQty - response.data.ibActualQty;
  }).catch((error) => { });
}

// 根据不同业务类型获取不同区域的站台
function getStationList() {
  stationParams.value.zoneId = props.registerInfo.zoneId;
  listStation(stationParams.value).then(response => {
    stationOptions.value = response.rows;
  }).catch(error => { });
}

// 入库登记(根据不同的单据类型调用不同的入库放行接口)
const goRegister = () => {
  console.log('goRegister', props.registerInfo);
  register.value.validate((valid) => {
    if (valid) {
      if (props.registerInfo.pageType === 'WIP') {
        ibWipRegister(registerData.value).then((response) => {
          proxy.$modal.msgSuccess(response.msg);
          refresh();
        }).catch((error) => { })
      } else if (props.registerInfo.pageType === 'FG') {
        ibFgRegister(registerData.value).then((response) => {
          proxy.$modal.msgSuccess(response.msg);
          refresh();
        }).catch((error) => { })
      } else if (props.registerInfo.pageType === 'RETURN') {
        ibReturnRegister(registerData.value).then((response) => {
          proxy.$modal.msgSuccess(response.msg);
          refresh();
        }).catch((error) => { })
      }
    }
  });
}

// 入库放行
const goRelase = () => {
  if (!registerData.value.contNo) return ElMessage.warning('请输入或者扫描待放行的容器条码')
  ibRelease({ contNo: registerData.value.contNo, creator: registerData.value.creator }).then((response) => {
    proxy.$modal.msgSuccess(response.msg);
  }).catch(error => { });
}

const refresh = () => { emit('refresh') }

getDetailInfo();
getStationList();
</script>
